package com.yjd.bi.report.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.yjd.bi.base.service.impl.BaseServiceImpl;
import com.yjd.bi.report.dao.IBiDatabaseInfoDao;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.model.BiEtlFromtableTotableModel;
import com.yjd.bi.report.service.IBiDatabaseInfoService;
import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.StringUtil;

/**
 * <b>description</b>：数据库信息业务实现<br>
 * <b>time</b>：2016-04-08 15:18:56 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@Service("biDatabaseInfoService")
public class BiDatabaseInfoServiceImpl extends BaseServiceImpl implements
		IBiDatabaseInfoService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public BiDatabaseInfoModel insert(BiDatabaseInfoModel model)
			throws Exception {
		this.validata(model);
		return this.biDatabasesInfoDao.insertModel(model, true);
	}

	public void validata(BiDatabaseInfoModel model) throws Exception {
		if (model == null || StringUtil.isEmpty(model.getTitle())
				|| StringUtil.isEmpty(model.getCode())
				|| StringUtil.isEmpty(model.getJdbc_driver())
				|| StringUtil.isEmpty(model.getJdbc_url())
				|| StringUtil.isEmpty(model.getJdbc_username())
				|| StringUtil.isEmpty(model.getJdbc_password())
				|| StringUtil.isEmpty(model.getDescription())
				|| model.getBs_type() == null) {
			FrameUtil
					.throwBaseException1("标题、编码、jdbc_driver、jdbc_url、jdbc_username、jdbc_password、库业务类型、描述都不能为空!");
		}
		model.setCode(model.getCode().toLowerCase());
		if (model.getBs_type() == 1
				&& (model.getData_change_log_database_info_id() == null || model
						.getData_change_log_database_info_id() == 0)) {
			FrameUtil.throwBaseException1("业务库必须配置日志变更记录库!");
		}

		BiDatabaseInfoModel tm = this.biDatabasesInfoDao.getModelOne(
				FrameUtil.newHashMap("code", model.getCode()), true);
		if ((tm!=null && model.getId() != null && !model.getId().equals(tm.getId()))
				|| (model.getId() == null && tm != null)) {
			FrameUtil.throwBaseException1(String.format("编码%s已使用，请换一个",
					model.getCode()));
		}

	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(BiDatabaseInfoModel model) throws Exception {
		this.validata(model);
		return this.biDatabasesInfoDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int delete(long id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("id", id);
		return this.biDatabasesInfoDao.deleteModel(paramMap, true);
	}

	@Resource
	private IBiDatabaseInfoDao biDatabasesInfoDao;

	@Override
	public IBaseDao getBaseDao() {
		return this.biDatabasesInfoDao;
	}

}
